import styles from "./index.module.scss";

import { Image } from "@arco-design/web-react";
import { useState, useEffect, useCallback } from "react";
import { useNavigate, useLocation } from "react-router-dom";

export default function CommonMenuBar({ 
  menuList: initialMenuList, 
  onMenuChange 
}) {
  const [menuList, setMenuList] = useState(initialMenuList);
  const navigate = useNavigate();
  const location = useLocation();

  // 在组件挂载和路由变化时，根据当前路由自动设置菜单激活状态
  useEffect(() => {
    if (!initialMenuList) return;

    // 从当前路径中提取路由key
    const pathSegments = location.pathname.split("/");
    const routeKey = pathSegments[pathSegments.length - 1];

    // 使用函数式更新，避免闭包陷阱
    setMenuList((prevMenuList) => {
      // 检查是否有匹配当前路由的菜单项
      let hasMatchedRoute = false;

      // 遍历菜单检查是否有匹配项
      for (const parentItem of prevMenuList) {
        if (parentItem.children?.some((child) => child.key === routeKey)) {
          hasMatchedRoute = true;
          break;
        }
      }

      // 如果找到了匹配的路由项，设置对应菜单项为激活
      if (hasMatchedRoute) {
        return prevMenuList.map((parentItem) => ({
          ...parentItem,
          children: parentItem.children?.map((child) => ({
            ...child,
            active: child.key === routeKey,
          })),
        }));
      }
      // 如果没有匹配的路由项，默认激活第一个菜单
      else {
        const updatedMenu = [...prevMenuList];
        // 确保有菜单和子菜单
        if (
          updatedMenu.length > 0 &&
          updatedMenu[0].children &&
          updatedMenu[0].children.length > 0
        ) {
          // 先将所有菜单项设置为非激活
          updatedMenu.forEach((parent) => {
            if (parent.children) {
              parent.children.forEach((child) => {
                child.active = false;
              });
            }
          });
          // 然后激活第一个菜单项
          updatedMenu[0].children[0].active = true;

          // 存储默认路由以便后续导航
          const defaultRoute = `${updatedMenu[0].children[0].key}`;
          
          // 使用setTimeout延迟导航，确保在当前渲染周期后执行
          setTimeout(() => {
            if (location.pathname !== defaultRoute) {
              navigate(defaultRoute);
            }
          }, 0);
        }
        return updatedMenu;
      }
    });
  }, [location.pathname, navigate, initialMenuList]);

  // 菜单点击处理函数
  const handleMenuClick = (menu, parentKey = null) => {
    // 在菜单点击时执行路由跳转
    if (parentKey) {
      const targetRoute = `/${menu.key}`;
      // 检查当前路由是否与目标路由相同，如果不同才执行跳转
      if (location.pathname !== targetRoute) {
        navigate(targetRoute);
      }
    }
    
    onMenuChange?.(menu, () => {
      // 回调：更新菜单状态
      if (parentKey) {
        // 如果是子菜单，只更新该子菜单的状态
        setMenuList((prev) =>
          prev.map((item) => {
            if (item.key === parentKey) {
              return {
                ...item,
                children: item.children.map((child) =>
                  child.key === menu.key
                    ? { ...child, active: true }
                    : { ...child, active: false }
                ),
              };
            }

            return {
              ...item,
              children: item.children.map((child) => {
                return { ...child, active: false };
              }),
            };
          })
        );
      }
    });
  };

  // 渲染子菜单组件
  const renderSubMenu = (subMenu, parentKey) => {
    return (
      <div className={styles.subMenu} key={subMenu.key}>
        <div
          className={`${styles.menuItem} ${subMenu.active ? "is-active" : ""}`}
          onClick={() => handleMenuClick(subMenu, parentKey)}
        >
          {subMenu.icon && (
            <Image className={styles.icon} src={subMenu.icon} preview={false} draggable={false} />
          )}
          <div className={styles.text}>{subMenu.title}</div>
        </div>
      </div>
    );
  };

  // 渲染主菜单组件
  const renderMainMenu = (menu) => {
    return (
      <div key={menu.key} className={styles.mainMenu}>
        <div
          className={`${styles.menuTitle} ${menu.active ? "is-active" : ""}`}
          onClick={() => handleMenuClick(menu)}
        >
          <div className={styles.titleText}>{menu.title}</div>
        </div>
        {menu.children &&
          menu.children.map((sub) => renderSubMenu(sub, menu.key))}
      </div>
    );
  };

  if (!menuList) return null;

  return (
    <div className={styles.menuBar}>
      {menuList.map((menu) => renderMainMenu(menu))}
    </div>
  );
}